<?php

/**
 *  分類原型
 */
class BaseCategories extends BaseMapper
{
    protected $_modelName               = '';  // '??????Category'
    protected $_dbTableName             = '';  // 'Application_Model_DbTable_??????Categories'

    /* ================================================================================
        access database
    ================================================================================ */

    /**
     *  add Category
     */
    public function addCategory( $model )
    {
        return $this->_save( $model, 'add' );
    }

    /**
     *  update Category
     */
    public function updateCategory( $model )
    {
        return $this->_save( $model, 'update' );
    }

    /**
     *  get Category
     */
    public function getCategory( $id, $userId=null, $status=BaseCategory::STATUS_ALL )
    {
        $model = $this->_find($id);

        if( BaseCategory::STATUS_ALL !== $status && $model->getStatus() !== $status ) {
            return false;
        }
        if( $userId && $model->getUserId() != $userId ) {
            return false;
        }
        return $model;
    }

    /**
     *  find many UserServiceCategories
     *  find 的方式為：包含提供上一層重要關聯索引值的查找, 並使用搜尋值 (searchKey) 的方式來取得資料
     */
    public function getCategories( $searchKey=null, $status=BaseCategory::STATUS_OPEN, $page=1, $rowCount=BaseMapper::DEFAULT_ROW_COUNT ) 
    {
        $opt = Array(
            'status'     => $status,
            '_searchKey' => $searchKey,
            '_page'      => $page,
            '_rowCount'  => $rowCount,
            '_orderBy'   => ' ordered_pages ASC , id ASC ',
        );
        return $this->_getByQuery($opt);
    }

    /**
     *  get count by "_getCategories" method
     */
    public function getNumCategories( $searchKey=null, $status=BaseCategory::STATUS_OPEN ) 
    {
        $opt = Array(
            'status'     => $status,
            '_searchKey' => $searchKey,
        );
        return $this->_getByQuery($opt,true);
    }

    /**
     *  get UserServiceCategory query
     */
    protected function _getByQuery( $opt, $isGetTotal=false )
    {
        $this->_checkOption($opt);
        $opt += Array(
            'keyName'      => (isset($opt['keyName'])      ?       ($opt['keyName'])      : NULL ),
            'name'         => (isset($opt['name'])         ?       ($opt['name'])         : NULL ),
            'description'  => (isset($opt['description'])  ?       ($opt['description'])  : NULL ),
            'status'       => (isset($opt['status'])       ? (int) ($opt['status'])       : NULL ),
            'orderedPages' => (isset($opt['orderedPages']) ? (int) ($opt['orderedPages']) : NULL ),
            'properties'   => (isset($opt['properties'])   ?       ($opt['properties'])   : NULL ),

            '_startDate'   => (isset($opt['_startDate'])   ?       ($opt['_startDate'])   : NULL ),
            '_endDate'     => (isset($opt['_endDate'])     ?       ($opt['_endDate'])     : NULL ),
            '_searchKey'   => (isset($opt['_searchKey'])   ?       ($opt['_searchKey'])   : NULL ),
            '_orderBy'     => (isset($opt['_orderBy'])     ?       ($opt['_orderBy'])     : ' id DESC ' ),
            '_page'        => (isset($opt['_page'])        ? (int) ($opt['_page'])        : 1 ),
            '_rowCount'    => (isset($opt['_rowCount'])    ? (int) ($opt['_rowCount'])    : BaseMapper::DEFAULT_ROW_COUNT ),
        );

        if( isset($opt['_orderBy']) ) {
            $opt['_orderBy'] = explode(',',$opt['_orderBy']);
        }

        if( isset($opt['_page']) && $opt['_page']<=1 ) {
            $opt['_page'] = 1;
        }

        $where = Array();
        if(isset( $opt['keyName']             )) { $where[] = $this->getDb()->getAdapter()->quoteInto(' key_name = ? '            , $opt['keyName']                 );  }
        if(isset( $opt['name']                )) { $where[] = $this->getDb()->getAdapter()->quoteInto(' name = ? '                , $opt['name']                 );  }
        if(isset( $opt['description']         )) { $where[] = $this->getDb()->getAdapter()->quoteInto(' description = ? '         , $opt['description']          );  }
        if(isset( $opt['status']              )) { $where[] = $this->getDb()->getAdapter()->quoteInto(' status = ? '              , $opt['status']               );  }
        if(isset( $opt['orderedPages']        )) { $where[] = $this->getDb()->getAdapter()->quoteInto(' ordered_pages = ? '       , $opt['orderedPages']         );  }
        if(isset( $opt['properties']          )) { $where[] = $this->getDb()->getAdapter()->quoteInto(' properties = ? '          , $opt['properties']           );  }

        if( $opt['_searchKey'] ) {
            // 注意: 特殊符號應該要變更一下 => "%" "_" 之類的
            $searchTerms[] = $this->getDb()->getAdapter()->quoteInto(' key_name    LIKE ? ', '%'.$opt['_searchKey'].'%' );
            $searchTerms[] = $this->getDb()->getAdapter()->quoteInto(' name        LIKE ? ', '%'.$opt['_searchKey'].'%' );
            $searchTerms[] = $this->getDb()->getAdapter()->quoteInto(' description LIKE ? ', '%'.$opt['_searchKey'].'%' );
            $where[] = ' ( '. join(' OR ',$searchTerms) . ' ) ';
        }

        // where from array to string
        $whereString = join(' AND ',$where);
        if(!$whereString) {
            $whereString = null;
        }

        // get total
        if( $isGetTotal ) {
            $select = $this->getDb()->select();
            $select->from( $this->getDb(), Array('COUNT(*) AS total') );
            if($whereString) {
                $select->where( $whereString );
            }
            $rows = $this->getDb()->fetchRow($select);
            $row = $rows->toArray();
            return (int) $row['total'];
        }

        //
        //echo $whereString;

        //
        if( NULL === $opt['_page'] ) {
            $rowset = $this->getDb()->fetchAll($whereString, $opt['_orderBy']);
        }
        else {
            $offset = ($opt['_page']-1) * $opt['_rowCount'];
            $rowset = $this->getDb()->fetchAll($whereString, $opt['_orderBy'], $opt['_rowCount'], $offset );
        }
        if( !$rowset ) {
            return NULL;
        }

        $models = Array();
        foreach( $rowset as $row ) {
            $models[] = $this->mapRow( $row->toArray() );
        }
        return $models;

    }

    /* ================================================================================
        about model object
    ================================================================================ */

    /**
     *  set mapRow by pure database record
     */
    public function MapRow($row)
    {
        //properties
        is_array($row["properties"])
            ? $row["properties"] = unserialize($row["properties"])
            : $row["properties"] = Array();

        $model = $this->getModel();
        $model->setId           ( $row['id']            );
        $model->setKeyName      ( $row['key_name']      );
        $model->setName         ( $row['name']          );
        $model->setDescription  ( $row['description']   );
        $model->setStatus       ( $row['status']        );
        $model->setOrderedPages ( $row['ordered_pages'] );
        $model->setProperties   ( $row['properties']    );
        return $model;
    }

}

